<template>
  <div id="ShoppingCart">
    <div id="div1">
        <div id="div2">
            <el-empty description="购物车是空的" :image-size="200" v-if="dataListDisPlay"></el-empty>
            <div v-else>
                <div id="div3">
                    <p id="p1">全部商品 {{totalNumber}}</p>
                </div>
                <div id="div4">
                    <el-row>
                        <el-col :span="4">
                            <div id="div5">
                                <input type="checkbox" class="input1" v-model="totalCheck" @click="wholeCheck()">全选
                            </div>
                        </el-col>
                        <el-col :span="10"><span class="span12">商品</span></el-col>
                        <el-col :span="2"><span class="span1">单价</span></el-col>
                        <el-col :span="3"><span class="span1">数量</span></el-col>
                        <el-col :span="3"><span class="span2">小计</span></el-col>
                        <el-col :span="2"><span class="span3">操作</span></el-col>
                    </el-row>
                </div>
                <div class="div6" v-for="(item,index) in dataList" :key="index">
                    <el-row v-if="item.is_no_diy === 0">
                        <el-col :span="4">
                            <div class="div8">
                                <input type="checkbox" class="input2" v-model="item.flag" @click="checkboxById(item.id,item.flag)">
                                <img :src="`${$imageUrl}?id=` + item.image_id.split(',')[0]" class="img1" @click="MainList(item.commodity_id)">
                            </div>
                        </el-col>
                        <el-col :span="10">
                            <div class="div7" @click="MainList(item.commodity_id)">{{item.back}}</div>
                            <div class="div9">{{item.commodity_name}}</div>
                        </el-col>
                        <el-col :span="2">
                            <span style="color: #9d9d9d;font-size: 12px;text-decoration: line-through;" class="span4">￥{{item.price}}</span>
                            <span class="span4">￥{{item.favorable_price}}</span>
                        </el-col>
                        <el-col :span="3">
                            <el-input-number size="mini" @change="changeNum(item.id,item.number,item.number*item.favorable_price)" v-model="item.number" :min="1" :max="200" class="elinput1"></el-input-number>
                        </el-col>
                        <el-col :span="3">
                            <span class="span5">￥{{item.number*item.favorable_price}}</span>
                        </el-col>
                        <el-col :span="2"><span class="span6" @click="delShoppingCartByUserId(item.id)">删除</span></el-col>
                    </el-row>
                    <el-row v-if="item.is_no_diy === 1">
                        <el-col :span="4">
                            <div class="div8">
                                <input type="checkbox" class="input2" v-model="item.flag" @click="checkboxById(item.id,item.flag)">
                                <img :src="`${$imageUrl}?id=` + item.diy_image_id" class="img1" @click="toDIYView(item.diy_id)">
                            </div>
                        </el-col>
                        <el-col :span="10">
                            <div  class="div7" @click="toDIYView(item.diy_id)">{{item.diy_details}}</div>
                            <div class="div9">{{item.diy_name}}</div>
                        </el-col>
                        <el-col :span="2">
                            <span style="color: #9d9d9d;font-size: 12px;text-decoration: line-through;" class="span4">￥{{item.diy_price}}</span>
                            <span class="span4">￥{{item.diy_favorable_price}}</span>
                        </el-col>
                        <el-col :span="3">
                            <el-input-number size="mini" @change="changeNum(item.id,item.number,item.number*item.diy_favorable_price)" v-model="item.number" :min="1" :max="200" class="elinput1"></el-input-number>
                        </el-col>
                        <el-col :span="3">
                            <span class="span5">￥{{item.number*item.diy_favorable_price}}</span>
                        </el-col>
                        <el-col :span="2"><span class="span6" @click="delShoppingCartByUserId(item.id)">删除</span></el-col>
                    </el-row>
                </div>
                <div id="div10">
                    <el-row>
                        <el-col :span="4">
                            <div id="div11">
                                <input type="checkbox" class="input1" v-model="totalCheck">全选
                            </div>
                        </el-col>
                        <el-col :span="12"><span class="span11" @click="delShoppingCart()">删除选中的商品</span></el-col>
                        <el-col :span="3"><span class="span8">已选择 <span id="span1">{{totalNum}}</span> 件商品</span></el-col>
                        <el-col :span="3"><span class="span7">总价：<span id="span2">￥{{totalPrice}}</span></span></el-col>
                        <el-col :span="2"><div id="div12" @click="toSubmitOrder()">去结算</div></el-col>
                    </el-row>
                </div>
            </div>
        </div>
      
    </div>
  </div>
</template>

<script>
export default {
  data() {
        return {
            // 数据列表
            dataList: [],
            // 用户商品数量
            totalNumber: '',
            // 购物车
            shoppingCart: {},
            // 用户id
            userId: window.sessionStorage.getItem('userId'),
            // 批量删除id
            arr: [],
            // 提交商品
            commodityArr: [],
            // 提交DIY
            DIYArr: [],
            // 购物车是否为空
            dataListDisPlay: false
        }
    },
    mounted() {
        this.shoppingCartByUserId()
        this.shoppingCartCountByUserId()
    },
    methods: {
        //商品列表跳转商品详情页面
        MainList(id) {
            this.$router.push({
                path: '/PageMain',
                query: { id: id }
            });
        },
        // 跳转到DIY商品详情页面
        toDIYView(id) {
            this.$router.push({
                path: "/DIYView",
                query: { diyId: id },
            });
        },
        // 修改选中单选框
        checkboxById (id,flag) {
            // 判断是否选中
            if (flag) {
                this.$axios.get('/shoppingCart/checkboxById', {
                    params: {
                        id: id
                    }
                }).then(res => {
                    if (res.data.flag) {
                        this.myMessage('success', res.data.data)
                    }else{
                        this.myMessage('error', res.data.data)
                    }
                }).catch(err => {
                    console.log(err)
                })
            } else {
                this.$axios.get('/shoppingCart/checkboxByIds', {
                    params: {
                        id: id
                    }
                }).then(res => {
                    if (res.data.flag) {
                        this.myMessage('success', res.data.data)
                    }else{
                        this.myMessage('error', res.data.data)
                    }
                }).catch(err => {
                    console.log(err)
                })
            }
        },
        // 修改全部选中单选框
        wholeCheck () {
            if (this.totalCheck === true) {
                this.dataList.filter( res =>{
                    // 查找选择框被选中的商品,并将它们返回给数组arr
                    if (res.flag === true) {
                        this.arr.push(res.id)
                    }
                })
                this.$axios.put('/shoppingCart/wholeCheck', this.arr).then(res => {
                    if (res.data.flag) {
                        this.arr = []
                        this.myMessage('success', res.data.data)
                    }else{
                        this.myMessage('error', res.data.data)
                    }
                }).catch(err => {
                    console.log(err)
                })
            } else {
                this.dataList.filter( res =>{
                    // 查找选择框被选中的商品,并将它们返回给数组arr
                        this.arr.push(res.id)
                })
                this.$axios.put('/shoppingCart/wholeChecks', this.arr).then(res => {
                    if (res.data.flag) {
                        this.arr = []
                        this.myMessage('success', res.data.data)
                    }else{
                        this.myMessage('error', res.data.data)
                    }
                }).catch(err => {
                    console.log(err)
                })
            }
        },
        // 跳转到我的订单页面
        toSubmitOrder() {
            let index = 0;
            this.dataList.filter( res =>{
                if (res.flag === true) {
                    if (res.is_no_diy === 0) {
                        this.commodityArr.push( { id: res.cid, number: res.number, commodity_name: res.commodity_name} )
                    } else {
                        this.DIYArr.push    ( { id: res.hid, number: res.number} )
                    }
                    index++
                }
            })
            if (index !== 0) {
                if (index === this.commodityArr.length) {
                    this.$router.push({
                        path: "/SubmitOrder",
                        query: { 
                            commodityArr: this.$Base64.encode(JSON.stringify(this.commodityArr)),
                            diyArr: this.$Base64.encode(JSON.stringify([]))
                        },
                    })
                } else if (index === this.DIYArr.length) {
                    this.$router.push({
                        path: "/SubmitOrder",
                        query: { 
                            diyArr: this.$Base64.encode(JSON.stringify(this.DIYArr)),
                            commodityArr: this.$Base64.encode(JSON.stringify([])),
                        },
                    })
                } else {
                    this.myMessage('error', '商品和diy不能同时选中')
                }
            } else {
                this.myMessage('error', '请选择')
            }
            this.commodityArr = []
            this.DIYArr = []
            index = 0
        },
        // 逻辑删除已经选中的商品
        delShoppingCart () {
            this.$confirm('此操作将删除选中商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.dataList.filter( res =>{
                    // 查找选择框被选中的商品,并将它们返回给数组arr
                    if (res.flag === true) {
                        this.arr.push(res.id)
                    }
                })
                this.$axios.put('/shoppingCart/delShoppingCart', this.arr).then(res => {
                    // 用户购物车商品数量
                    if (res.data.flag) {
                        this.shoppingCartByUserId()
                        this.shoppingCartCountByUserId()
                        this.arr = []
                        this.myMessage('success', res.data.data)
                    }else{
                        this.myMessage('error', res.data.data)
                    }
                }).catch(err => {
                    console.log(err)
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        // 根据id逻辑删除
        delShoppingCartByUserId (data) {
            this.$confirm('此操作将删除该商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.delete('/shoppingCart/delShoppingCartByUserId', {
                    params: {
                        id: data
                    }
                }).then(res => {
                    // 用户购物车商品数量
                    if (res.data.flag) {
                        this.shoppingCartByUserId()
                        this.shoppingCartCountByUserId()
                        this.myMessage('success', res.data.data)
                    }else{
                        this.myMessage('error', res.data.data)
                    }
                }).catch(err => {
                    console.log(err)
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        // 点击数量发生改变
        changeNum (id,number,totalPrices) {
            // 填充数据
            this.shoppingCart.id = id
            this.shoppingCart.number = number
            this.shoppingCart.totalPrices = totalPrices
            this.$axios.put("/shoppingCart/changeNum", this.shoppingCart).then((res) => {
                if (res.data.flag) {
                    this.shoppingCart = {}
                    this.myMessage('success', res.data.data)
                }else{
                    this.myMessage('error', res.data.data)
                }
            }).catch(err => {
                console.log(err);
            });
        },
        // 查询用户购物车商品数量
        shoppingCartCountByUserId () {
            this.$axios.get("/shoppingCart/shoppingCartCountByUserId", {
                params: {
                    userId: this.userId
                }
            }).then((res) => {
                // 用户购物车商品数量
                if (res.data.flag) {
                    this.totalNumber = res.data.data;
                }else{
                    this.myMessage('error', res.data.data)
                }
            }).catch(err => {
                console.log(err);
            });
        },
        // 查询购物车信息
        shoppingCartByUserId () {
            this.$axios.get("/shoppingCart/shoppingCartByUserId", {
                params: {
                    userId: this.userId
                }
            }).then((res) => {
                // 购物车信息
                if (res.data.flag) {
                    this.dataList = res.data.data;
                    if (this.dataList.length !== 0) {
                        this.dataListDisPlay = false
                        this.dataList.forEach(item => {
                            if (item.flag === 'false') {
                                item.flag = false;
                            } else {
                                item.flag = true;
                            }
                        })
                    }else{
                        this.dataListDisPlay = true
                    }
                }
            }).catch(err => {
                console.log(err);
            });
        },
        // 封装弹窗
        myMessage (type, message) {
            this.$message({
                message: message,
                type: type
            })
        }
    },
    // 计算属性
    computed:{
        totalNum(){    
            // 选中商品的数量
            let arr = this.dataList.filter( res =>{
                // 查找选择框被选中的商品,并将它们返回给数组arr
                return res.flag === true;     
            });
            // 选中商品的数量就等于arr的长度
            return arr.length;     
        },
        // 全选按钮
        totalCheck:{
            // 通过商品的选择框控制全选的框子     
            get(){
                 // 当 选中商品的数量等于商品的总数量是，表示商品被全选了
                if(this.totalNum === this.dataList.length){
                    // 全选框选中
                    return true;     
                }else{
                    // 全选框未选中
                    return false;
                }
            },
            // 操作全选框，改变所有商品的选中情况
            set(e){
                if(e){
                    this.dataList.forEach(item => {
                        // 让购物车的每一项都选中
                        return item.flag = true;
                    })
                }else{
                    // 全选框没有被选中      
                    this.dataList.forEach(item => {
                        // 购物车的每一项都未选中
                        return item.flag = false;
                    })
                }
            }
        },
        // 总价
        totalPrice(){
            let sum = 0;
            this.dataList.forEach(res =>{
                // 判断商品是否被选中
                if(res.flag){
                    // 计算总价
                    if (res.is_no_diy === 0){
                        sum += res.number*res.favorable_price;
                    }else{
                        sum += res.number*res.diy_favorable_price;
                    }
                }
            })
            return sum;
        }
    }
}
</script>

<style scoped>
    #div12{
        width: 100%;
        height: 50px;
        background: #e54346;
        line-height: 50px;
        text-align: center;
        font-size: 18px;
        font-family: Microsoft YaHei;
        cursor: pointer;
        border: 1px solid #e54346;
        color: #fff;
    }
    #div10{
        width: 100%;
        height: 50px;
        font-size: 14px;
        border: 1px solid #d4d4d4;
        margin-bottom: 20px;
        font-size: 12px;
    }
    .span6:hover{
        color: #e2231a;
    }
    .span11:hover{
        color: #e2231a;
    }
    .div7:hover{
        color: #e2231a;
    }
    .elinput1{
        display: block;
        margin: auto;
    }
    /* 设置输入框的高度 */
    .div6 /deep/ .el-input-number--mini {
        width: 80px;
        line-height: 26px;
    }
    .div6 /deep/ .el-input-number .el-input__inner {
        width: 80px;
        height: 24px;
        padding: 0 28px;
    }
    
    .div6 /deep/ .el-input-number__decrease:hover:not(.is-disabled)~.el-input .el-input__inner:not(.is-disabled), .div6 /deep/ .el-input-number__increase:hover:not(.is-disabled)~.el-input .el-input__inner:not(.is-disabled){
        border-color: #409EFF;
    }
    .div6 /deep/ .el-input-number__decrease:hover {
        border-color: #409EFF;
    }
    .div6 /deep/ .el-input-number__increase:hover{
        border-color: #409EFF;
    }
    .div6 /deep/ .el-input-number__increase {
        height: 24px;
        width: 24px;
        background-color: transparent
    }
    
    .div6 /deep/ .el-input-number__decrease {
        width: 24px;
        height: 24px;
        background-color: transparent
    }
    .div9{
        width: 130px;
        height: 20px;
        color: #333;
        overflow : hidden;
        word-wrap: break-word;
        float: left;
        line-height: 20px;
        margin-left: 20px;
    }
    .div7{
        width: 208px;
        height: 40px;
        color: #333;
        overflow : hidden;
        word-wrap: break-word;
        margin: 0;
        float: left;
        line-height: 20px;
        cursor:pointer;
    }
    .img1{
        width: 80px;
        height: 80px;
        display: block;
        float: left;
        cursor:pointer;
    }
    .div6{
        width: 100%;
        height: 105px;
        padding-top: 15px;
        margin: 10px 0;
        border: 1px solid #d4d4d4;
        border-top: 2px solid #aaa;
        font-size: 14px;
    }
    .span5{
        display: block;
        text-align: right;
        line-height: 24px;
        margin-right: 50px;
        font-family: verdana;
        font-weight: 700;
    }
    .span6{
        display: block;
        text-align: left;
        line-height: 24px;
        cursor:pointer;
    }
    .span4{
        display: block;
        text-align: center;
        line-height: 24px;
        color: #333;
        font-size: 14px;
    }
    .span8{
        display: block;
        text-align: right;
        line-height: 50px;
        color: #999;
    }
    #span1{
        font-size: 16px;
        color: #e2231a;
        line-height: 50px;
        font-family: verdana;
        font-weight: 700;
    }
    #span2{
        font-size: 16px;
        color: #e2231a;
        line-height: 50px;
        font-family: verdana;
        font-weight: 700;
    }
    .span7{
        display: block;
        text-align: right;
        line-height: 50px;
        margin-right: 20px;
        color: #999;
    }
    .span2{
        display: block;
        text-align: right;
        line-height: 32px;
        margin-right: 50px;
    }
    .span3{
        display: block;
        text-align: left;
        line-height: 32px;
    }
    .span1{
        display: block;
        text-align: center;
        line-height: 32px;
    }
    .span12{
        display: block;
        text-align: left;
        line-height: 32px;
        font-size: 12px;
    }
    .span11{
        display: block;
        text-align: left;
        line-height: 50px;
        font-size: 12px;
        cursor:pointer;
    }
    .div8{
        height: 18px;
        line-height: 18px;
        width: 122px;
        padding-left: 11px;
    }
    #div11{
        height: 18px;
        line-height: 18px;
        padding-top: 16px;
        width: 122px;
        padding-left: 11px;
    }
    #div5{
        height: 18px;
        line-height: 18px;
        padding-top: 7px;
        width: 122px;
        padding-left: 11px;
    }
    .input2{
        display: block;
        float: left;
        margin: 0 8px 0 0;
        padding: 0;
        vertical-align: middle;
    }
    .input1{
        margin: 0 8px 0 0;
        padding: 0;
        vertical-align: middle;
    }
    #div4{
        width: 100%;
        height: 32px;
        padding: 5px 0;
        background: #dedede;
        border: 1px solid #e9e9e9;
        font-size: 14px;
        color: #434343;
        margin-bottom: 10px;
    }
    #p1{
        color: #e2231a;
        font-weight: 700;
        font-size: 16px;
        line-height: 40px;
    }
    #div3{
        width: 100%;
        height: 40px;
        margin-top: 10px;
    }
    #div2{
        width: 70%;
        margin: auto;
    }
    #div1{
        width: 100%;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
        -webkit-appearance: none;
    }

    input[type="number"] {
        width: 40px;
        text-align: center;
    }
    .totalNum{
        font-size: 22px;
        color: #f00;
    }
</style>